﻿using AutoMapper;
using MediatR;
using Warehouse.Api.Write.AllCation.Command.Checksheet;
using Warehouse.Domian.Model;
using Warehouse.ErrorCode;
using Warehouse.Infrastructrue.Implenment;

namespace Warehouse.Api.Write.AllCation.Hanlder
{
    public class AddChecksheetCommandHanlder : IRequestHandler<AddChecksheetCommand, ApiResult<int>>
    {
        public readonly IBaseRepostity<Checksheet> _stockingRepostity;
        public readonly IMapper mapper;
        public readonly ILogger<AddChecksheetCommandHanlder> logger;

        public AddChecksheetCommandHanlder(IBaseRepostity<Checksheet> stockingRepostity, IMapper mapper, ILogger<AddChecksheetCommandHanlder> logger)
        {
            _stockingRepostity = stockingRepostity;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加盘点信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(AddChecksheetCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                var model = mapper.Map<Checksheet>(request);
                int r = _stockingRepostity.InsertAsync(model).Result;
                if (r > 0)
                {
                    result.Msg = "添加成功";
                    logger.LogInformation("添加盘点信息成功");
                    result.Data = r;
                    result.Code = ApiEume.Success;
                }
                else
                {
                    result.Msg = "添加失败";
                    logger.LogInformation("添加盘点信息失败");
                    result.Data = r;
                    result.Code = ApiEume.Error;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加盘点记录失败");
            }
            return Task.FromResult(result);
        }
    }
}
